<template>
  <div>
    <el-drawer class="drawer" :title="title" :visible.sync="visible" size="50%" direction="rtl"
               :wrapperClosable="false">
      <div class="container">
        <div class="container-body" ref="containerBody">
          <el-form ref="form" :model="form" label-width="120px" :rules="rules">
            <div class="section">
              <div class="section-title">基本信息</div>
              <div class="section-content">
                <el-form-item label="优惠券类型" prop="couponType" key="couponType">
                  <el-select v-model="form.couponType" @change="handleCouponTypeChange" placeholder="请选择优惠券类型">
                    <el-option :label="dict.label" :value="dict.value" v-for="dict in dict.type.coupon_type"
                               :key="dict.value"></el-option>
                    <!--                    <el-option label="满减券" value="1"></el-option>-->
                    <!--                    <el-option label="无门槛券" value="2"></el-option>-->
                  </el-select>
                </el-form-item>
                <el-form-item label="所属机构" prop="tenantId" key="tenantId">
                  <el-select v-model="form.tenantId" placeholder="请选择机构" clearable filterable
                             @change="handleTenantChange">
                    <el-option v-for="item in tenantList" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="优惠券名称" prop="couponName" key="couponName">
                  <el-input v-model="form.couponName" show-word-limit :maxlength="20"
                            placeholder="请输入优惠券名称"></el-input>
                </el-form-item>
                <el-form-item label="优惠券折扣" prop="couponDenomination" key="couponDenomination3"
                              v-if="form.couponType === '3'">
                  <el-input v-model="form.couponDenomination" v-input.float="1" maxlength="3"
                            @blur="(e)=>form.couponDenomination=e.target.value===''?null:Number(e.target.value)"
                            placeholder="只能是数值，1-9.9，限1位小数"
                            @change="handleCouponDenominationChange"></el-input>
                </el-form-item>
                <el-form-item label="优惠券面额" prop="couponDenomination" key="couponDenomination1" v-else>
                  <el-input v-model="form.couponDenomination" v-input.float="2" maxlength="8"
                            @blur="(e)=>form.couponDenomination=e.target.value===''?null:Number(e.target.value)"
                            placeholder="只能是数值，0.01-10000，限2位小数"
                            @change="handleCouponDenominationChange"></el-input>
                </el-form-item>
                <el-form-item label="标签" prop="couponLabel" key="couponLabel">
                  <el-input v-model="form.couponLabel" show-word-limit :maxlength="10"
                            placeholder="请输入标签，如：满200减20"></el-input>
                </el-form-item>
                <el-form-item label="总发行量" prop="totalCirculation" key="totalCirculation">
                  <el-input v-model="form.totalCirculation" v-input.intp
                            @blur="(e)=>form.totalCirculation=e.target.value===''?null:Number(e.target.value)"
                            placeholder="只能输入正整数" :disabled="totalCirculationUnlimited"></el-input>
                  <el-checkbox v-model="totalCirculationUnlimited">无限制</el-checkbox>
                </el-form-item>
              </div>
            </div>
            <div class="section">
              <div class="section-title">规则范围</div>
              <div class="section-content">
                <el-form-item label="使用门槛" prop="couponThreshold" key="couponThreshold"
                              v-if="form.couponType === '1'||form.couponType === '3'">
                  <el-input v-model="form.couponThreshold" v-input.float="2"
                            @blur="(e)=>form.couponThreshold=e.target.value===''?null:Number(e.target.value)"
                            placeholder="满多少钱可以使用，限2位小数" @change="handleCouponThresholdChange">
                    <template slot="prepend">满</template>
                    <template slot="append">元可用</template>
                  </el-input>
                </el-form-item>
                <el-form-item label="使用门槛" key="couponType" required v-if="form.couponType === '2'">
                  无门槛
                </el-form-item>
                <el-form-item label="活动时间" prop="activityStartTime" key="activityStartTime">
                  <el-date-picker type="datetimerange" v-model="activityTime" range-separator="至"
                                  start-placeholder="开始日期" end-placeholder="结束日期"
                                  :default-time="['00:00:00', '23:59:59']"
                                  value-format="yyyy-MM-dd HH:mm:ss" @change="handleActivityTimeChange">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="券使用有效期" prop="validityPeriodType" key="validityPeriodType">
                  <el-row>
                    <el-col :span="6">
                      <el-radio v-model="form.validityPeriodType" label="1">活动时间内</el-radio>
                    </el-col>
                    <el-col :span="14" style="display: flex;align-items: center;">
                      <el-radio v-model="form.validityPeriodType" label="2">领取后</el-radio>
                      <el-input v-model="form.validityPeriodDay" :disabled="form.validityPeriodType !== '2'" v-input.int
                                @blur="(e)=>form.validityPeriodDay=e.target.value===''?null:Number(e.target.value)" style="margin-left: 10px;"
                                placeholder="请输入天数">
                        <template slot="append">天内有效</template>
                      </el-input>
                    </el-col>
                  </el-row>
                </el-form-item>
                <el-form-item label="适用范围" prop="applyScope" key="applyScope">
                  <el-radio-group v-model="form.applyScope" @change="handleApplyScopeChange">
                    <el-radio :label="dict.value" v-for="dict in dict.type.apply_scope" :key="dict.value">{{
                        dict.label
                      }}
                    </el-radio>
                  </el-radio-group>
                  <div class="applyScope-content">
                    <div class="applyScope-content-item" v-if="form.applyScope === '2'">
                      <div class="applyScope-content-item-title">房源：</div>
                      <div class="applyScope-content-item-content">
                        <el-button type="primary" @click.stop="handleSelectHouse" :disabled="!form.tenantId">+选择
                        </el-button>
                        已选（{{ form.couponHouseList.length }}）
                      </div>
                    </div>
                    <div class="applyScope-content-item" v-if="form.applyScope === '3'">
                      <div class="applyScope-content-item-title">指定区域：</div>
                      <div class="applyScope-content-item-content">
                        <el-cascader :options="areaList" filterable clearable ref="areaPicker" v-model="cityCode"
                                     :props="{multiple: true, emitPath: false, showAllLevels: true, label: 'name', value: 'id'}"
                                     :show-all-levels="true"
                                     @change="handleAreaChange"></el-cascader>
                      </div>
                    </div>
                  </div>
                </el-form-item>
                <el-form-item label="领取方式" prop="pickupMethod" key="pickupMethod">
                  <el-checkbox-group v-model="pickupMethodMultiple" @change="handlePickupMethodChange">
                    <el-checkbox v-for="item in pickupMethodList.filter(item=>item.type==='multiple')"
                                 :label="item.value" :key="item.value">{{
                        item.label
                      }}
                    </el-checkbox>
                  </el-checkbox-group>
                  <el-radio-group v-model="pickupMethodSingle" @change="handlePickupMethodChange">
                    <el-radio v-for="item in pickupMethodList.filter(item=>item.type==='single')" :label="item.value"
                              :key="item.value" :disabled="item.value === '3' && totalCirculationUnlimited">
                      <span>
                        {{ item.label }}
                        <!--                                                  <el-input v-if="item.value === '3' && pickupMethodSingle === '3'"-->
                        <!--                                                            v-model="form.verificationNumber" v-input.int-->
                        <!--                                                            @blur="(e)=>form.verificationNumber=Number(e.target.value)"-->
                        <!--                                                            style="margin-left: 10px;width: 200px;"-->
                        <!--                                                            placeholder="请输入核销码数量">-->
                        <!--                                                    <template slot="append">张</template>-->
                        <!--                                                  </el-input>-->
                      </span>
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="是否叠加使用" prop="superpositionType" key="superpositionType">
                  <el-radio-group v-model="form.superpositionType">
                    <el-radio label="0">否</el-radio>
                    <el-radio label="1">是</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="退款成功失效" prop="refundLapsedType" key="refundLapsedType">
                  <el-radio-group v-model="form.refundLapsedType">
                    <el-radio label="0">否</el-radio>
                    <el-radio label="1">是</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="使用说明" prop="couponInstruction" key="couponInstruction">
                  <el-button type="text" @click.stop="handleAutoGenerate">点击生成</el-button>
                  <editor v-model="form.couponInstruction" :min-height="192"/>
                </el-form-item>
              </div>
            </div>
          </el-form>
        </div>
        <div class="container-footer">
          <el-button type="primary" @click.stop="handleSubmit">保存</el-button>
          <el-button @click.stop="visible = false">取消</el-button>
        </div>
      </div>

      <!--   选择房屋弹窗   -->
      <select-house :show.sync="showSelectHouse" :isMultiple="true" :data="form" :seleted-list="form.couponHouseList"
                    api-type="listRoomByAllocation" :api-params="apiParams"
                    @success="handleSelectHouseSuccess"></select-house>
    </el-drawer>
  </div>
</template>

<script>
import {listDepartment} from "@/api/sys-enterprise";
import {areaInfo} from "@/api/system/config";
import selectHouse from "@/views/components/common/select-house/index.vue";
import {debounce} from "@/utils";
import {addCoupon, editCoupon, getCouponDetail} from "@/api/marketing/coupon";

export default {
  name: "CouponAdd",
  dicts: ['apply_scope', 'coupon_type'],
  components: {
    selectHouse
  },
  props: {
    title: {
      type: String,
      default: "新增优惠券"
    },
    show: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: () => ({})
    },
  },
  data() {
    return {
      // 选择房屋弹窗状态
      showSelectHouse: false,
      // 选中房屋弹窗筛选条件数据
      apiParams: {
        apartmentState: "0", // 上架状态：0已上架 1已下架
        tenantId: "", // 所属机构ID
        houseIds: "", // 房源ID集合
      },
      // 机构列表
      tenantList: [],
      cityCode: [], //区域编码
      areaList: [], //区域列表
      // pickupMethod: [], //领取方式
      pickupMethodMultiple: [], //多选领取方式
      pickupMethodSingle: '', //单选领取方式
      pickupMethodList: [
        {label: "领券中心", value: "1", type: "multiple"},
        {label: "商品详情", value: "2", type: "multiple"},
        {label: "核销码", value: "3", type: "single"},
        {label: "指派", value: "4", type: "single"}
      ], //领取方式列表
      // 表单数据
      form: {},
      activityTime: [], //活动时间
      totalCirculationUnlimited: false, //总发行量是否无限制
      // 表单验证规则
      rules: {
        couponName: [
          {required: true, message: '请输入优惠券名称', trigger: 'blur'},
          {min: 1, max: 20, message: '优惠券名称长度在 1 到 20 个字符', trigger: 'blur'}
        ],
        couponType: [
          {required: true, message: '请选择优惠券类型', trigger: 'change'}
        ],
        couponThreshold: [
          {required: true, message: '请输入使用门槛', trigger: 'blur'},
        ],
        tenantId: [
          {required: true, message: '请选择所属机构', trigger: 'change'}
        ],
        couponDenomination: [
          {required: true, message: '请输入优惠券面额', trigger: 'blur'},
          {
            validator: (rule, value, callback) => {
              if (this.form.couponType === '3') {
                if (value < 0.01 || value > 9.9) {
                  callback(new Error('折扣券面额必须在1-9.9之间'));
                }
                callback();
              } else if (this.form.couponType === '1') {
                if (value < 0.01) {
                  callback(new Error('优惠券面额必须大于等于0.01'));
                } else if (value > 10000) {
                  callback(new Error('优惠券面额必须小于等于10000'));
                } else {
                  callback();
                }
              } else {
                callback();
              }

            }, trigger: 'blur'
          }
        ],
        couponLabel: [
          {required: true, message: '请输入标签', trigger: 'blur'}
        ],
        totalCirculation: [
          // {required: true, message: '请输入总发行量', trigger: 'blur'},
          {
            validator: (rule, value, callback) => {
              if(this.totalCirculationUnlimited){
                callback()
              }
              if(!value){
                callback(new Error('请输入总发行量'))
              }
              callback();
            }, trigger: 'blur'
          }
        ],
        activityStartTime: [
          {required: true, message: '请选择活动时间', trigger: 'change'},
          {
            validator: (rule, value, callback) => {
              if (!this.activityTime.length) {
                callback(new Error('请选择活动时间'));
              }
              callback();
            }, trigger: 'change'
          }
        ],
        validityPeriodType: [
          {required: true, message: '请选择有效期类型', trigger: 'change'}
        ],
        validityPeriodDay: [
          {required: true, message: '请输入有效期天数', trigger: 'blur'},
          {type: 'number', message: '有效期天数必须为数字', trigger: 'blur'},
          {min: 1, max: 99999, message: '有效期天数必须在 1 到 99999 之间', trigger: 'blur'}
        ],
        applyScope: [
          {required: true, message: '请选择适用范围', trigger: 'change'},
          {
            validator: (rule, value, callback) => {
              if (value === '2' && !this.form.couponHouseList.length) {
                callback(new Error('请选择适用房源'));
              } else if (value === '3' && !this.form.cityCode) {
                callback(new Error('请选择适用区域'));
              } else {
                callback();
              }
            }, trigger: 'blur'
          }
        ],
        cityCode: [
          {required: true, message: '请选择区域', trigger: 'change'}
        ],
        pickupMethod: [
          {required: true, message: '请选择领取方式', trigger: 'blur'},
          {
            validator: (rule, value, callback) => {
              if (this.pickupMethodMultiple.length === 0 && this.pickupMethodSingle === '') {
                callback(new Error('请选择领取方式'));
              }
              // if (this.pickupMethodSingle === '3' && !this.form.verificationNumber) {
              //   callback(new Error('请输入核销码数量'));
              // }
              callback();
            }, trigger: 'change'
          }
        ],
        verificationNumber: [
          {required: true, message: '请输入核销码数量', trigger: 'blur'},
          {type: 'number', message: '核销码数量必须为数字', trigger: 'blur'},
          {min: 1, max: 99999, message: '核销码数量必须在 1 到 99999 之间', trigger: 'blur'}
        ],
        couponInstruction: [
          {required: true, message: '请输入使用说明', trigger: 'blur'},
          {
            validator: (rule, value, callback) => {
              if (this.form.couponInstruction === "<p><br></p>") {
                callback(new Error('请输入使用说明'));
              }
              callback();
            }, trigger: 'blur'
          }
        ]
      }
    }
  },
  computed: {
    visible: {
      get() {
        return this.show
      },
      set(val) {
        this.$emit("update:show", val)
      }
    },
    useDesc: {
      get() {
        // 使用范围
        let applyScopeHtml = ""
        let applyScope = this.dict.type.apply_scope.find(item => item.value === this.form.applyScope)
        if (applyScope) {
          applyScopeHtml = `<p>仅适用于${applyScope.label}，请在有效期内使用，过期自动失效。</p>`
        }
        //使用时间
        let useTimeHtml = ""
        if (this.form.activityStartTime && this.form.activityEndTime) {
          useTimeHtml = `<p>使用时间：${this.form.activityStartTime}至${this.form.activityEndTime}。</p>`
        }
        //使用规则
        let useRuleHtml = ""

        if (this.form.couponThreshold !== null && this.form.couponDenomination && this.form.couponType !== '2') {
          if (this.form.couponType === '1') {
            useRuleHtml = `<p>使用规则：满${this.form.couponThreshold}元减${this.form.couponDenomination}元。</p>`
          }
          if (this.form.couponType === '3') {
            useRuleHtml = `<p>使用规则：满${this.form.couponThreshold}元打${this.form.couponDenomination}折。</p>`
          }
        } else if (this.form.couponType === '2') {
          useRuleHtml = `<p>使用规则：无门槛券。</p>`
        }
        //领取规则
        let pickupRuleHtml = `<p>领取规则：每人限领一张。</p>`
        return applyScopeHtml + useTimeHtml + useRuleHtml + pickupRuleHtml
      },
      set(val) {
        console.log('useDesc', val)
      }
    }

  },
  watch: {
    visible(val) {
      if (val) {
        this.$nextTick(() => {
          console.log('this.$refs', this.$refs.containerBody)
          this.$refs.containerBody.scrollTop = 0;
        })
        this.init();
      }
    },
  },
  created() {
    this.getAreaInfo();
  },
  methods: {
    init() {
      this.getDepartmentList();
      this.reset();
      if (this.data.couponId) {
        this.form = {...this.data}
        this.activityTime = [this.data.activityStartTime, this.data.activityEndTime];
        this.cityCode = this.data.cityCode ? this.data.cityCode.split(",") : [];
        if (this.data.pickupMethod) {
          let pickupMethod = this.data.pickupMethod.split(",").filter(item => {
            return (item === '3' || item === '4')
          })
          if (pickupMethod.length > 0) {
            this.pickupMethodSingle = pickupMethod[0]
            this.pickupMethodMultiple = []
          } else {
            this.pickupMethodSingle = ''
            this.pickupMethodMultiple = this.data.pickupMethod.split(",")
          }
        }
        // this.pickupMethodMultiple = this.data.pickupMethod ? this.data.pickupMethod.split(",") : [];

      }
      // 重新提交
      if (this.data.isReSubmit && this.data.isReSubmit === true) {
        delete this.form['couponId']
      }

      if(this.data.totalCirculation === 0){
        this.totalCirculationUnlimited = true
        this.form.totalCirculation = null
      }


    },
    // 重置表单
    reset() {
      this.form = {
        tenantId: null, //机构ID
        couponName: "", //优惠券名称
        couponType: "1", //优惠价类型(1.满减券,2.无门槛券)
        couponState: "1", //优惠券状态(1.待提交,2.待审核,3.待开始,4.活动中,5.已结束,6.已驳回)
        couponDenomination: null, //优惠券面额
        couponThreshold: null, //使用门槛
        couponLabel: "", //优惠券标签
        totalCirculation: null, //总发行量
        activityStartTime: "", //活动开始时间
        activityEndTime: "", //活动结束时间
        validityPeriodType: "1", //有效期类型(1.活动时间内,2.领取几天内有效)
        validityPeriodDay: null, //领取天数内有效,validityPeriodType为2则传
        applyScope: "1", //使用范围(1.全场通用,2.指定房源,3.指定区域)
        cityCode: null, //区域编码,applyScope为3则传
        pickupMethod: "", //领取方式(1.领券中心,2.商品详情,3.核销码,4.指派)
        pickupMethodName: "", //领取方式名称
        verificationNumber: null, //核销码数量,pickupMethod为3则传
        superpositionType: "0", //是否叠加使用(0:否,1.是)
        refundLapsedType: "0", //退款成功失效(0:否,1.是)
        couponInstruction: "", //使用说明
        tenantName: null, //机构名称
        remainingNumber: null,
        couponHouseList: [] //优惠券关联房源数据集合,applyScope为2则传
      }
      this.cityCode = [];
      this.pickupMethodMultiple = [];
      this.pickupMethodSingle = '';
      this.activityTime = [];
      this.totalCirculationUnlimited = false;
      this.resetForm("form");
    },
    // 获取区域信息
    getAreaInfo() {
      areaInfo().then((res) => {
        this.areaList = res.data;
      });
    },
    // 查询机构列表
    getDepartmentList() {
      listDepartment().then(response => {
        this.tenantList = response.data.map(item => {
          return {
            label: item.tenantName,
            value: item.tenantId
          }
        });
      });
    },
    // 机构改变
    handleTenantChange(val) {
      this.form.couponHouseList = [];
      if (val) {
        this.form.tenantId = val
        this.form.tenantName = this.tenantList.find(item => item.value === val).label
      } else {
        this.form.tenantId = null
        this.form.tenantName = ''
      }
    },
    // 优惠券类型改变
    handleCouponTypeChange(val) {
      console.log("this.form.couponInstruction", this.form.couponInstruction)
    },
    // 优惠券面额改变
    handleCouponDenominationChange(val) {
    },
    // 使用门槛改变
    handleCouponThresholdChange(val) {
    },
    // 活动时间改变
    handleActivityTimeChange(val) {
      console.log("val", val)
      if (val && val.length) {
        this.form.activityStartTime = val[0];
        this.form.activityEndTime = val[1];
        this.activityTime = [val[0], val[1]];
      } else {
        this.form.activityStartTime = "";
        this.form.activityEndTime = "";
        this.activityTime = [];
      }
    },
    // 适用范围改变
    handleApplyScopeChange(val) {
      this.form.couponHouseList = [];
      this.form.cityCode = null;
      this.cityCode = [];
    },
    // 领取方式改变
    handlePickupMethodChange(val) {
      console.log('val', val)
      if (val.length > 0) {
        if (Array.isArray(val)) {
          this.pickupMethodSingle = ''
          this.form.pickupMethod = val.join(",")
          this.form.pickupMethodName = this.pickupMethodList.filter(item => val.includes(item.value)).map(item => item.label).join(",")
        } else {
          this.pickupMethodMultiple = []
          this.form.pickupMethod = val
          this.form.pickupMethodName = this.pickupMethodList.find(item => item.value === val).label
        }

      } else {
        this.form.pickupMethod = ""
        this.form.pickupMethodName = ""
      }
      if (!val.includes('3')) {
        this.form.verificationNumber = null
      }
    },
    // 选择房源弹窗
    handleSelectHouse() {
      this.apiParams.tenantId = this.form.tenantId;
      this.showSelectHouse = true;

    },
    // 选择房源成功回调
    handleSelectHouseSuccess(val) {
      this.form.couponHouseList = val;
    },
    // 区域选择
    handleAreaChange(value) {
      this.form.cityCode = value.join(",");
    },
    // 使用说明生成
    handleAutoGenerate() {
      this.$confirm('是否生成使用说明？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form.couponInstruction = this.useDesc;
      }).catch(() => {
        // do nothing
      });

    },
    handleSubmit: debounce(function () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let params = {...this.form}
          if(this.totalCirculationUnlimited){
            params.totalCirculation = 0
          }
          if (this.form.couponId) {
            editCoupon(params).then(response => {
              this.$message.success(response.msg || "操作成功");
              this.visible = false;
              this.$emit("success");
              this.reset();
            })
          } else {
            addCoupon(params).then(response => {
              this.$message.success(response.msg || "操作成功");
              this.visible = false;
              this.$emit("success");
              this.reset();
            })
          }

        }
      });
    }, 1000, true),
  }
}
</script>

<style lang="scss" scoped>
.container {
  overflow: hidden;
  height: 100%;
  position: relative;

  .container-body {
    overflow-y: auto;
    height: 90%;
  }

  .container-footer {
    height: 10%;
    display: flex;
    align-items: center;
    border-top: 1px solid #e4e4e4;
    padding: 10px;
    justify-content: center;
  }
}

.section {
  padding: 10px;

  .section-title {
    padding: 8px 16px;
    background-color: #ecf8ff;
    border-radius: 4px;
    border-left: 5px solid #50bfff;
    margin-bottom: 20px;
    font-size: 16px;
    font-weight: bold;
  }
}

.applyScope-content {
  .applyScope-content-item {
    margin-top: 20px;
    display: flex;
    align-items: center;

    .applyScope-content-item-title {
      margin-right: 10px;
    }

    .applyScope-content-item-content {
      display: flex;
      align-items: center;

      .el-button {
        margin-right: 10px;
      }
    }
  }
}
</style>
